#include<iostream>
#include<unistd.h>
#include<cassert>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstdio>
#include<cstdlib>

using namespace std;

int main()
{
    int fds[2];
    int n=pipe(fds);
    assert(n==0);
    pid_t fd=fork();
    assert(fd>=0);
    if(fd==0)
    {
        close(fds[0]);
        const char*s="我是子进程，正在给你发消息";
        int cnt=0;
        while(true)
        {
            ++cnt;
            char buf[1024];
            snprintf(buf,sizeof(buf),"child->parent:%s[%d]%d",s,getpid(),cnt);
            write(fds[1],buf,strlen(buf));
            sleep(1);
            if(cnt==10) break;
        }
        close(fds[1]);
        cout<<"子进程关闭写端"<<endl;
        exit(0);
    }
    close(fds[1]);
    while(true)
    {
        char buf[1024];
        ssize_t s=read(fds[0],buf,sizeof(buf)-1);
        if(s>0)
        {
            buf[s]=0;
            cout<<"# "<<buf<<endl<<"*pid:"<<getpid()<<endl;
        }
        else if(s==0)
        {
            cout<<"读取结束"<<endl;
            break;
        }
    }
    close(fds[0]);
    cout<<"父进程关闭读端"<<endl;
    waitpid(fd,nullptr,0);
    return 0;
}